package com.pw.study.jdbc.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: study_spring
 * @description: 连接池
 * @author: future
 * @create: 2021-03-24 21:59
 **/
public class JdbcPool {
    private static LinkedList<Connection> pool =new LinkedList<>();
    private static Integer POOLSIZE=5;

    //2.定义连接url
    private static String url = "jdbc:mysql://localhost:3306/study?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false";
    //3.定义账号和密码
    private static String user = "root";
    private static String password = "123456";

    public JdbcPool(){
        //1、装载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        initConnection();
    }

    private static void initConnection() {

        for (int i = 0; i <POOLSIZE ; i++) {
            Connection connection= createConnection();
            pool.add(connection);
            System.out.println("init pool: "+ connection.hashCode());
        }
    }
    //定义一个方法返回connection对象
    public static Connection getConnection(){
        Connection connection =null;
        if(pool.size()>0){
            connection =pool.removeFirst();
            System.out.println("pool get :"+connection.hashCode());

        }else {
            connection=createConnection();
            System.out.println("self create get :"+connection.hashCode());
        }
        return connection;
    }
    //释放连接
    public static void returnConnection(Connection connection) {
        System.out.println("释放："+connection.hashCode());
        if(pool.size()<10){
            pool.addLast(connection);
        }else {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    //定义一个方法返回connection对象
    private static Connection createConnection(){
        Connection con=null;

            //4.获得连接对象
            try {
                con = DriverManager.getConnection(url, user, password);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        return con;
    }


}
